package com.koron.css2.serviceManage.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserAdminBusiBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.UserAdminBusiMapper;
import com.koron.util.Constant;
import com.koron.util.DBSourceUtils;
import com.koron.util.JsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

/**
 * 根据用户表刷新结构化地址的所属营业所
 * @author leejie
 * @date 2022/4/14
 */
public class UserAdminBusiAreaList implements ServerInterface {
    private static Logger logger = LogManager.getLogger(UserAdminBusiAreaList.class);

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        MessageBean<Void> result = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "刷新营业所成功", void.class);
        String group = userInfo.getCurWaterCode();
        logger.info("当前水司：{}",group);
        try {
            String dbEnv = DBSourceUtils.getDbEnv(group,true);
            UserAdminBusiMapper mapper = factory.getMapper(UserAdminBusiMapper.class,dbEnv);
            UserAdminBusiMapper mapper1 = factory.getMapper(UserAdminBusiMapper.class,"_default");
            //获取当前水司下的营业区域ID列表
            List<String> busiAreasId = mapper1.getBusiAreaByGroup(group);
            logger.info("当前 {} 水司下的营业区域 {}",group,JsonUtils.objectToJson(busiAreasId));
            int i= 0;
            for (String busiAreaId : busiAreasId) {
                //获取用户表中的结构化地址id和营业区域ID
                List<UserAdminBusiBean> beanList = mapper.getUserAdminAndBusiArea(busiAreaId);
                logger.info("用户表中的结构化地址id和营业区域ID:  "+JsonUtils.objectToJson(beanList));
                //更新结构化地址表中的所属营业所
                if (beanList.size() != 0){
                    for (UserAdminBusiBean userAdminBusiBean : beanList) {
                        i = mapper1.updateBusiAreaByAdminBusi(userAdminBusiBean);
                        logger.info("更新 {} , {} 成功，",userAdminBusiBean.getBusiArea(),userAdminBusiBean.getClientConAddr());
                    }
                }
            }
        }catch (Exception e){
            logger.error("刷新营业所失败：{}",e.getMessage());
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "刷新营业所失败", void.class);
        }
        return result;
    }
}
